/*****************************************
 World of Warcraft 3D Board Game Project
 Team: Cheng, Logan, Thomas, Tyler
 Class: GSP 360
******************************************/

#include <windows.h>
#include <mmsystem.h>
#include <d3d9.h>
#include <d3dx9tex.h>
#include <ctime>
#include <stdio.h>
#include <cmath>
#include <string>
#include "hud.h"
#include "sound.h"

//conversion from 'double' to 'int', possible loss of data	
#pragma warning( disable : 4244 )
//conversion from 'double' to 'float', possible loss of data
#pragma warning( disable : 4305 )

// Define X and Y Mouse positions
#define GET_X_LPARAM(lParam) ((int)(short)LOWORD(lParam))
#define GET_Y_LPARAM(lParam) ((int)(short)HIWORD(lParam))

// change the row/column, height/width of screen
#define ROW 10
#define COL 10
#define HEIGHT 480
#define WIDTH  640

// direct3D functions
HINSTANCE hInst;  // holds the instance for this app
LPDIRECT3DTEXTURE9      g_pTexture   = NULL;
LPDIRECT3D9             pD3D;           // the direct3D object
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

// coloring material
D3DMATERIAL9            red;
D3DMATERIAL9            black;
D3DMATERIAL9            blue;
D3DMATERIAL9            green;
D3DMATERIAL9			yellow;
D3DMATERIAL9            hordeRed;
ID3DXMesh *boxMesh, *sphereMesh;

//Input Variables
int mouseX;
int mouseY;
int curHordePosX, curHordePosY, curAlliancePosX, curAlliancePosY;
int option = 0;
float hordeX, hordeY, allianceX, allianceY;
char coordinateX[256] = {'\0'};
float distance;
bool mouseClick;
double multiX, multiY, boundryX, boundryY;
float botX, botY;

// camera variables
D3DXMATRIX matView;                                     // the view matrix
D3DXMATRIX matProj;                                     // the projection matrix
D3DXVECTOR3 cameraPosition;                     // the position of the camera
D3DXVECTOR3 cameraLook;                         // where the camera is pointing
float cameraX = 0.0;
float cameraY = 15.0;
float cameraZ = -15.0;

//Windows Functions
bool initWindow(HINSTANCE hInstance);
bool initDirect3D(HWND hwnd);
void shutdown(void);

//Initalize and display HUD
void SetHudCamera(float WindowWidth, float WindowHeight);
void drawHud();
LPD3DXFONT font2;

//Mouse Input
void doClick(float, float);

// Coloring the board
enum {RED, BLACK};

// Draw Functions
void drawSquare(float &x, float &z);
void drawBoard(int x, int y);
void drawHorde(float x, float y);  //TJD
void drawAlliance(float x, float y); //TJD
void drawBot(float x, float y);
void PrintText(char *text);

//Battle Functions
void battleMelee();
void battleMagic();
void moveBot();
bool HmelAttack = false, HmagAttack = false, AmelAttack, AmagAttack;

//Collision Function
bool collision(int x, int y);

//Lighting and Cameras
void createLighting(void);
void createPointLight(void);
void createCamera(float nearClip, float farClip);
void moveCamera(D3DXVECTOR3 vec);
void pointCamera(D3DXVECTOR3 vec);

//Light Flickers variables
#define FLICKER_COUNT	4
#define MAX_COLOR		255.0f
D3DLIGHT9 light;
D3DLIGHT9 light2;
D3DLIGHT9 light3;
int lred[FLICKER_COUNT]		= {255,252,245,231};
int lgreen[FLICKER_COUNT]	= {255,103,80, 28};
int lblue[FLICKER_COUNT]	= {  0,  3, 5,22};
int bred[FLICKER_COUNT]		= {24,22,213,29};
int bgreen[FLICKER_COUNT]	= {220,65,38,226};
int bblue[FLICKER_COUNT]	= {231,233,217,113};
int lcount = 0;


/*************************************************************************
* WinMain
* entry point
*************************************************************************/
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
	srand ((unsigned)time(NULL));

	human.setStats("Banis", 30, 4, 4, 3, 3);
	orc.setStats("Garg", 20, 5, 2, 4, 2);

	hordeX = -3.4; hordeY = -2.4;
	allianceX = 3.4; allianceY = -2.4;
	curHordePosX = 180; curHordePosY = 270;
	curAlliancePosX = 460; curAlliancePosY = 270;
	botX = 0.5 ;botY = 4;
	mouseClick = false;

        // call our function to init and create our window
        if (!initWindow(hInstance))
        {
                MessageBox(NULL, "Unable to create window", "ERROR", MB_OK);
                return false;
        }

        // init direct3d
        if (!initDirect3D(wndHandle))
        {
                MessageBox(NULL, "Unable to init Direct3D", "ERROR", MB_OK);
                shutdown();
                return false;
        }

		// initialize DirectSound
		if (!initDirectSound(wndHandle))
		{
			MessageBox(NULL, "Unable to init DirectSound", "ERROR", MB_OK);
			return false;
		}

		// load a wave file into a directsound buffer
		DSBuffer[1] = LoadWaveToSoundBuffer("orgTheme.wav");
		DSBuffer[2] = LoadWaveToSoundBuffer("orc_click.wav");
		DSBuffer[3] = LoadWaveToSoundBuffer("orc_crit.wav");
		DSBuffer[4] = LoadWaveToSoundBuffer("alliance_click.wav");
		DSBuffer[5] = LoadWaveToSoundBuffer("alliance_crit.wav");


		if (!DSBuffer)
		return false;

		playSoundLoop(DSBuffer[1]);
		
		// setup the vertex buffer and add the triangle to it.
		hudBoxBack1(432.0f, 503.0f, 42.0f, 578.0f);
		hudBoxBack(435.0f, 500.0f, 45.0f, 575.0f);
		hudBoxAttack(440.0f, 458.0f, 399.0f, 475.0f);
		hudBoxMagic(461.0f, 479.0f, 399.0f, 475.0f);
		hudBoxMove(450.0f, 468.0f, 499.0f, 563.0f);

        // create the lighting for this scene
        createLighting();

        // Create and add the box
        D3DXCreateBox(pd3dDevice, 1.0f, 1.0f, 1.0f, &boxMesh, NULL);
        D3DXComputeNormals(boxMesh, NULL);

        // create and add the sphere
        D3DXCreateSphere(pd3dDevice, 1, 20, 20, &sphereMesh, NULL);
        D3DXComputeNormals(sphereMesh, NULL);

        // Create a D3DX font object
        D3DXCreateFont( pd3dDevice, 20, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, TEXT("Arial"), &font1 );

		// Create a D3DX font object
		D3DXCreateFont( pd3dDevice, 20, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, TEXT("Arial"), &font2 );

		// Create a D3DX font object
		D3DXCreateFont( pd3dDevice, 30, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, TEXT("Arial"), &font3 );

    // Main message loop:
    // Enter the message loop
    MSG msg;
    ZeroMemory( &msg, sizeof(msg) );
    while( msg.message!=WM_QUIT )
    {

		if (orc.getHealth() <= 0 || human.getHealth() <= 0)
        {
				if(orc.getHealth() <= 0)
				{
					MessageBox(NULL, "Alliance Wins!!", "~~~~  WINNER  ~~~~", MB_OK);
					return false;
				}
				
				if(human.getHealth() <= 0)
				{
					MessageBox(NULL, "Horde Wins!!", "~~~~  WINNER  ~~~~", MB_OK);
					return false;
				}
        }


		//Mouse Input
		if (msg.message == WM_MOUSEMOVE) 
			{
					//Take Mouse Data and seperate the Loword and Hiword
					mouseX = LOWORD(msg.lParam);
					mouseY = HIWORD(msg.lParam);
					//Scaling Factor for the X and Y values becuase windows in dumb
					mouseX = mouseX * 1.014263074;
					mouseY = mouseY * 1.0787;
			}

        // check for messages
        if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
        {
            TranslateMessage( &msg );
            DispatchMessage( &msg );
        }
        // this is called when no messages are pending
        else
        {
                // call our render function
                pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(255,255,255), 1.0f, 0 );

                pd3dDevice->BeginScene();

                // create the camera
                createCamera(1.0f, 750.0f);             // near clip plane, far clip plane
                pointCamera(D3DXVECTOR3(0.0f, 0.0f, 0.0f)); // default (0.0f, 0.0f, 0.0f)
                moveCamera(D3DXVECTOR3(cameraX, cameraY, cameraZ));

				//Create Lighting
				//Flicker Lights
				//if (lcount++ == FLICKER_COUNT) lcount = 0;

				//light2.Ambient.r = light2.Diffuse.r = bred[lcount]/MAX_COLOR;
				//light2.Ambient.g = light2.Diffuse.g = bgreen[lcount]/MAX_COLOR;
				//light2.Ambient.b = light2.Diffuse.b = bblue[lcount]/MAX_COLOR;

				////light2.Position = D3DXVECTOR3( meshMat._41, meshMat._42, meshMat._43 );
				pd3dDevice->SetLight(2, &light3 );

                // call function to draw the board and pieces
				drawBoard(ROW, COL);
				drawHorde(hordeX, hordeY);
				drawAlliance(allianceX, allianceY);
				drawBot(botX, botY);
				sprintf_s(coordinateX, "Option = %d", option);
				PrintText(coordinateX);

				//	fightatk(Alliance, Horde);
               
				//Initalizes a 2D camera and displays hud
                SetHudCamera(640, 480);
                pd3dDevice->SetRenderState( D3DRS_ZENABLE, FALSE );
                pd3dDevice->SetRenderState(D3DRS_LIGHTING,FALSE);

				//Background HUD
				drawVB(g_pVB3);
				drawVB(g_pVB0);
				drawVB(g_pVB);
				drawVB(g_pVB1);
				drawVB(g_pVB2);
                drawHud();

				
				if(HmelAttack == true)
				{
					drawHCombatLog();
				}
				if(AmelAttack == true)
				{
					drawACombatLog();
				}

                pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );
                pd3dDevice->SetRenderState(D3DRS_LIGHTING,TRUE);
                               
				//END SCENE
                pd3dDevice->EndScene();
                pd3dDevice->Present( NULL, NULL, NULL, NULL );  
        }
	}

        font1->Release();
        // shutdown the directx manager
        shutdown();

        return (int) msg.wParam;
}

/*************************************************************************
* initDirect3D
* initialize direct3D
*************************************************************************/
bool initDirect3D(HWND hwnd)
{
        HRESULT hr;

        if( NULL == ( pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
        {
                return false;
        }

        D3DPRESENT_PARAMETERS d3dpp;
		ZeroMemory( &d3dpp, sizeof(d3dpp) );
		d3dpp.Windowed = TRUE;
		d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
		d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
        d3dpp.BackBufferCount  = 1;
        d3dpp.BackBufferHeight = 480;
        d3dpp.BackBufferWidth  = 640;
        d3dpp.hDeviceWindow    = hwnd;
        d3dpp.EnableAutoDepthStencil = TRUE;
        d3dpp.AutoDepthStencilFormat = D3DFMT_D16;

		 hr = pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd,
                             D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                             &d3dpp, &pd3dDevice );
        if FAILED (hr)
	    {
        return false;
	    }

        // Set the default render states
        pd3dDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
        pd3dDevice->SetRenderState(D3DRS_NORMALIZENORMALS, TRUE);
        pd3dDevice->SetRenderState( D3DRS_ZENABLE, TRUE );

        return true;
}

/*************************************************************************
* createLighting
* sets the lights for this scene
*************************************************************************/
void createLighting(void)
{
        // set the ambient lighting to red
        pd3dDevice->SetRenderState(D3DRS_AMBIENT, D3DCOLOR_XRGB(255, 0, 0));

        // Create and turn on a directional light
		D3DXVECTOR3 vDir( 0.3f, 0.0f, 0.0f );
		light.Type         = D3DLIGHT_DIRECTIONAL;
		light.Diffuse.r    = light.Diffuse.g  = light.Diffuse.b  = 0.5f;
		light.Ambient.r    = light.Ambient.g  = light.Ambient.b  = 0.3f;
		D3DXVec3Normalize( (D3DXVECTOR3*)&light.Direction, &vDir );
		light.Attenuation0 = light.Attenuation1 = light.Attenuation2 = 0.0f;
		light.Range        = sqrtf(FLT_MAX);
		pd3dDevice->SetLight(0, &light );
		pd3dDevice->LightEnable(0, TRUE);

		// Create and turn on a point light
		light2.Type         = D3DLIGHT_POINT;
		light2.Diffuse.r    = 1.0f;
		light2.Diffuse.g  = light2.Diffuse.b  = 1.0f;
		light2.Ambient.r    = 0.0f;
		light2.Ambient.g  = light2.Ambient.b  = 1.0f;
		light2.Attenuation0 = light2.Attenuation1 = light2.Attenuation2 = 0.3f;
		light2.Position     = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
		light2.Range        = 3.5f;
		pd3dDevice->SetLight(1, &light2 );
		pd3dDevice->LightEnable(1, TRUE );

        // red
        ZeroMemory(&hordeRed, sizeof(D3DMATERIAL9));
        hordeRed.Diffuse.r = 0.545f;
        hordeRed.Ambient.r = 0.545f;
        hordeRed.Diffuse.g = 0.0f;
        hordeRed.Ambient.g = 0.0f;
        hordeRed.Diffuse.b = 0.0f;
        hordeRed.Ambient.b = 0.0f;
        hordeRed.Power = 8.0f;

		// black
        ZeroMemory(&red, sizeof(D3DMATERIAL9));
        red.Diffuse.r = 1.0f;
        red.Ambient.r = 1.0f;
        red.Diffuse.g = 0.0f;
        red.Ambient.g = 0.0f;
        red.Diffuse.b = 0.0f;
        red.Ambient.b = 0.0f;
        red.Power = 8.0f;   

        // black
        ZeroMemory(&black, sizeof(D3DMATERIAL9));
        black.Diffuse.r = 0.0f;
        black.Ambient.r = 0.0f;
        black.Diffuse.g = 0.0f;
        black.Ambient.g = 0.0f;
        black.Diffuse.b = 0.0f;
        black.Ambient.b = 0.0f;
        black.Power = 8.0f;    

        // blue
        ZeroMemory(&blue, sizeof(D3DMATERIAL9));
        blue.Diffuse.r = 0.0f;
        blue.Ambient.r = 0.0f;
        blue.Diffuse.g = 0.0f;
        blue.Ambient.g = 0.0f;
        blue.Diffuse.b = 1.0f;
        blue.Ambient.b = 1.0f;
        blue.Power = 8.0f;

        // green
        ZeroMemory(&green, sizeof(D3DMATERIAL9));
        green.Diffuse.r = 0.0f;
        green.Ambient.r = 0.0f;
        green.Diffuse.g = 1.0f;
        green.Ambient.g = 1.0f;
        green.Diffuse.b = 0.0f;
        green.Ambient.b = 0.0f;
        green.Power = 8.0f;

		// yellow
        ZeroMemory(&yellow, sizeof(D3DMATERIAL9));
        yellow.Diffuse.r = 1.0f;
        yellow.Ambient.r = 1.0f;
        yellow.Diffuse.g = 1.0f;
        yellow.Ambient.g = 1.0f;
        yellow.Diffuse.b = 0.0f;
        yellow.Ambient.b = 0.0f;
        yellow.Power = 8.0f;
}

/*************************************************************************
* shutdown
* releases the direct3d interfaces
*************************************************************************/
void shutdown(void)
{
    if( pd3dDevice != NULL)
        {
        pd3dDevice->Release();
                pd3dDevice = NULL;
        }
    if( pD3D != NULL)
        {
        pD3D->Release();
                pD3D = NULL;
        }
}

/*************************************************************************
* initWindow
* creates and shows a 640x480 window
*************************************************************************/
bool initWindow(HINSTANCE hInstance)
{
        WNDCLASSEX wcex;

        wcex.cbSize = sizeof(WNDCLASSEX);
        wcex.style                      = CS_HREDRAW | CS_VREDRAW;
        wcex.lpfnWndProc        = (WNDPROC)WndProc;
        wcex.cbClsExtra         = 0;
        wcex.cbWndExtra         = 0;
        wcex.hInstance          = hInstance;
        wcex.hIcon                      = 0;
        wcex.hCursor            = LoadCursor(NULL, IDC_ARROW);
        wcex.hbrBackground      = (HBRUSH)(COLOR_WINDOW+1);
        wcex.lpszMenuName       = NULL;
        wcex.lpszClassName      = "World of Warcraft - Board Game";
        wcex.hIconSm            = 0;
        RegisterClassEx(&wcex);

        wndHandle = CreateWindow("World of Warcraft - Board Game",
                                                         "World of Warcraft - Board Game",
                                                         WS_OVERLAPPEDWINDOW,
                                                         CW_USEDEFAULT,
                                                         CW_USEDEFAULT,
                                                         WIDTH,
                                                         HEIGHT,
                                                         NULL,
                                                         NULL,
                                                         hInstance,
                                                         NULL);
   if (!wndHandle)
      return false;
   
   ShowWindow(wndHandle, SW_SHOW);
   UpdateWindow(wndHandle);

   return true;
}

/*************************************************************************
* WndProc
* the windows procedure for this application
*************************************************************************/
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
        switch (message)
        {
                case WM_DESTROY:
                        PostQuitMessage(0);
                        break;

				case WM_LBUTTONDOWN:
				mouseClick = true;
				if (option > 0)
					doClick(mouseX, mouseY);
				if (mouseX > 400 && mouseX < 475 && mouseY > 440 && mouseY < 458)
					option = 1;
				if (mouseX > 400 && mouseX < 475 && mouseY > 462 && mouseY < 480)
					option = 2;
				if (mouseX > 500 && mouseX < 562 && mouseY > 450 && mouseY < 468)
					option = 3;
				break;

                //3 moveCamera(D3DXVECTOR3(0.0f, 15.0f, -15.0f));
                case WM_KEYDOWN:
                switch (wParam)
                {
                //case VK_UP:
                //        cameraY -= 1.5;
                //        break;
                //case VK_DOWN:
                //        cameraY += 1.5;
                //        break;

                //NEED TO FIX HOW IT PUSHES AWAY Z WHEN MOVING -TJD
                //case VK_LEFT:
                //        cameraX -= 1.5;
                //        break;
                //case VK_RIGHT:
                //        cameraX += 1.5;
                //        break;
				/**/
				case '1':
						option = 1;
						break;

				case '2':
						option = 2;
						break;	
				case '3':
						option = 3;
						break;	
				case 'Q':
						turn = 1;
						break;
				case 'W':
						turn = 2;
						break;
				case 'N':
						playSound(DSBuffer[2]);
						break;
				case 'M':
						playSound(DSBuffer[5]);
						break;
				case VK_BACK:
						stopSound(DSBuffer[1]);
						break;
				// increase volume
				case VK_OEM_PLUS:
						if(curVolume < DSBVOLUME_MAX)
						{
							curVolume += 500;
						}
						DSBuffer[1]->SetVolume(curVolume);
						break;
				// decrease volume
				case VK_OEM_MINUS:	
						if(curVolume > DSBVOLUME_MIN)
						{
							curVolume -= 500;
						}
						DSBuffer[1]->SetVolume(curVolume);
						break;
					
                }
        }
        return DefWindowProc(hWnd, message, wParam, lParam);
}

/*************************************************************************
* createCamera
* creates a virtual camera
*************************************************************************/
void createCamera(float nearClip, float farClip)
{
        //Here we specify the field of view, aspect ration and near and far clipping planes.
    D3DXMatrixPerspectiveFovLH(&matProj, D3DX_PI/4, 640/480, nearClip, farClip);
    pd3dDevice->SetTransform(D3DTS_PROJECTION, &matProj);

}

/*************************************************************************
* moveCamera
* moves the camera to a position specified by the vector passed as a
* parameter
*************************************************************************/
void moveCamera(D3DXVECTOR3 vec)
{
        cameraPosition = vec;
}

/*************************************************************************
* pointCamera
* points the camera a location specified by the passed vector
*************************************************************************/
void pointCamera(D3DXVECTOR3 vec)
{
        cameraLook = vec;

        D3DXMatrixLookAtLH(&matView, &cameraPosition,           //Camera Position
                                 &cameraLook,           //Look At Position
                                 &D3DXVECTOR3(0.0f, 1.0f, 0.0f));               //Up Direction

        pd3dDevice->SetTransform(D3DTS_VIEW, &matView);
}

void drawSquare(float &x, float &z)
{

        D3DXMATRIX meshMat, meshScale, meshRotate, meshTranslate;

        D3DXMatrixTranslation(&meshTranslate, x, 0.0, z);

        //D3DXMatrixRotationY(&meshRotate, timeGetTime()/500.0f);

        D3DXMatrixScaling(&meshScale, 1.0f, 1.0f, 1.0f);

       
        D3DXMatrixMultiply(&meshMat, &meshScale, &meshTranslate);
        //D3DXMatrixMultiply(&meshMat, &meshMat, &meshRotate);

        pd3dDevice->SetTransform(D3DTS_WORLD, &meshMat);

        boxMesh->DrawSubset(0);        
}

// In order to draw equal on both side, x and y is divided by 2
void drawBoard(int x, int y)
{
	int colorBox = BLACK;
	for(float r = -4.5; r <= 4.5; r++)
	{
			if(colorBox == BLACK)
			{
				pd3dDevice->SetMaterial(&green);
				colorBox = RED;
			}
			else if(colorBox == RED)
			{
				pd3dDevice->SetMaterial(&green);
				colorBox = BLACK;
			}
		for(float c = -5; c < 5; c++)
		{
			if(colorBox == BLACK)
			{
				pd3dDevice->SetMaterial(&black);
				colorBox = RED;
			}
			else if(colorBox == RED)
			{
				pd3dDevice->SetMaterial(&green);
				colorBox = BLACK;
			}
			drawSquare(r, c);
		}
	}
}
// Draw Horde toons
// Add by Cheng, draw horde as sphere for testing purpose.
void drawHorde(float x, float y)
{
	D3DXMATRIX meshMat, meshScale, meshRotate, meshTranslate;

	D3DXMatrixTranslation(&meshTranslate, x, 1.0f, y);
	//D3DXMatrixRotationY(&meshRotate, timeGetTime()/500.0f);
	D3DXMatrixScaling(&meshScale, 0.4f, 0.4f, 0.4f);

	D3DXMatrixMultiply(&meshMat, &meshScale, &meshTranslate);
	//D3DXMatrixMultiply(&meshMat, &meshMat, &meshRotate);

	pd3dDevice->SetTransform(D3DTS_WORLD, &meshMat);

	pd3dDevice->SetMaterial(&hordeRed);

	sphereMesh->DrawSubset(0);
}


//Draw Alliance toons -- TJD, modify by Cheng
void drawAlliance(float x, float y)
{
	D3DXMATRIX meshMat, meshScale, meshRotate, meshTranslate;

	D3DXMatrixTranslation(&meshTranslate, x, 1.0f, y);
	//D3DXMatrixRotationY(&meshRotate, timeGetTime()/500.0f);
	D3DXMatrixScaling(&meshScale, 0.4f, 0.4f, 0.4f);

	D3DXMatrixMultiply(&meshMat, &meshScale, &meshTranslate);
	//D3DXMatrixMultiply(&meshMat, &meshMat, &meshRotate);

	pd3dDevice->SetTransform(D3DTS_WORLD, &meshMat);

	pd3dDevice->SetMaterial(&blue);

	sphereMesh->DrawSubset(0);
}

void doClick(float x, float y)
{
	int voice;
	if(mouseClick)
	{
		boundryX = 32;
		boundryY = 13;
		multiX = 32;
		multiY = 13;

		if (turn == 1)
		{
			if (option == 1 && collision(x, y))
			{
				battleMelee();
				if(orc.getCrit() == true)
				{
					voice = (rand() % 2 + 2);
					playSound(DSBuffer[voice]);
				}
				turn++;
				option = 0;
			}
			else if (option == 2 && collision(x, y))
			{
				battleMagic();
				turn++;
				option = 0;
			}
			else if (option == 3)
			{
				for (int p = hordeY; p < 5; p++)
				{
					multiX = multiX * 1.035;
					multiY = multiY * 1.072;
				}
				multiX = multiX / 2;
				multiY = multiY / 2;
				if (fabs(curHordePosY - y) < multiY && !collision(x, y))
				{
					if (fabs(curHordePosX - x) > multiX && fabs(curHordePosX - x) < (multiX * 3))
					{
						if (curHordePosX - x > 0)
						{
							hordeX--;
							curHordePosX = curHordePosX - (multiX * 2);
							turn++;
							option = 0;
						}
						else if (x - curHordePosX > 0)
						{
							hordeX++;
							curHordePosX = curHordePosX + (multiX * 2);
							turn++;
							option = 0;
						}
					}
				}
				else if (fabs(curHordePosY - y) > multiY && fabs(curHordePosX - x) < multiX && !collision(x, y))
				{
					if (curHordePosY - y > 0)
					{
						for (int p = hordeY + 1; p < 5; p++)
						{
							boundryX = boundryX * 1.035;
							boundryY = boundryY * 1.072;
						}
						if (fabs(curHordePosY - y) < (boundryY + multiY))
						{
							hordeY++;
							curHordePosY = curHordePosY - (multiY + (boundryY / 2));
							turn++;
							option = 0;
						}
					}
					else if (y - curHordePosY > 0)
					{
						for (int p = hordeY - 1; p < 5; p++)
						{
							boundryX = boundryX * 1.035;
							boundryY = boundryY * 1.072;
						}
						if (fabs(curHordePosY - y) < (boundryY + multiY))
						{
							hordeY--;
							curHordePosY = curHordePosY + (multiY + (boundryY / 2));
							turn++;
							option = 0;
						}
					}
				}
			}
		}
		else
		{
			if (option == 1 && collision(x, y))
			{
				battleMelee();
				if(human.getCrit() == true)
				{
					voice = (rand() % 2 + 4);
					playSound(DSBuffer[voice]);
				}
				turn = 1;
				option = 0;
			}
			else if (option == 2 && collision(x, y))
			{
				battleMagic();
				turn = 1;
				option = 0;
			}
			else if (option == 3)
			{
				for (int p = allianceY; p < 5; p++)
				{
					multiX = multiX * 1.035;
					multiY = multiY * 1.072;
				}
				multiX = multiX / 2;
				multiY = multiY / 2;
				if (fabs(curAlliancePosY - y) < multiY)
				{
					if (fabs(curAlliancePosX - x) > multiX && fabs(curAlliancePosX - x) < (multiX * 3) && !collision(x, y))
					{
						if (curAlliancePosX - x > 0)
						{
							allianceX--;
							curAlliancePosX = curAlliancePosX - (multiX * 2);
							turn=1;
							option = 0;
						}
						else if (x - curAlliancePosX > 0)
						{
							allianceX++;
							curAlliancePosX = curAlliancePosX + (multiX * 2);
							turn=1;
							option = 0;
						}
					}
				}
				else if (fabs(curAlliancePosY - y) > multiY && fabs(curAlliancePosX - x) < multiX && !collision(x, y))
				{
					if (curAlliancePosY - y > 0)
					{
						for (int p = allianceY + 1; p < 5; p++)
						{
							boundryX = boundryX * 1.035;
							boundryY = boundryY * 1.072;
						}
						if (fabs(curAlliancePosY - y) < (boundryY + multiY))
						{
							allianceY++;
							curAlliancePosY = curAlliancePosY - (multiY + (boundryY / 2));
							turn=1;
							option = 0;
						} 
					}
					else if (y - curAlliancePosY > 0)
					{
						for (int p = allianceY - 1; p < 5; p++)
						{
							boundryX = boundryX * 1.035;
							boundryY = boundryY * 1.072;
						}
						if (fabs(curAlliancePosY - y) < (boundryY + multiY))
						{
							allianceY--;
							curAlliancePosY = curAlliancePosY + (multiY + (boundryY / 2));
							turn=1;
							option = 0;
						}
					}
				}
			}
		}
		mouseClick = false;
	}
}



void battleMelee()
{
	damage = 0;
	if(turn == 1)
	{
		orc.meleeAttack();
		human.meleeDefense();

		if((orc.getAttackDamage() > human.getArmorLevel()))
		{
			damage = (orc.getAttackDamage() - human.getArmorLevel());
			human.minusHp(damage);
		}
		HmelAttack = true;
		AmelAttack = false;
	}
	else
	{
		human.meleeAttack();
		orc.meleeDefense();

		if((human.getAttackDamage() > orc.getArmorLevel()))
		{
			damage = (human.getAttackDamage() - orc.getArmorLevel());
			orc.minusHp(damage);
		}
		HmelAttack = false;
		AmelAttack = true;
	}
}


void battleMagic()
{
	damage = 0;
	if(turn == 1)
	{
		orc.magicAttack();
		human.magicResist();

		if((orc.getMagicDamage() > human.getResistLevel()))
		{
			damage = (orc.getMagicDamage() - human.getResistLevel());
			human.minusHp(damage);
		}
	}
	else
	{
		human.magicAttack();
		orc.magicResist();

		if((human.getMagicDamage() > orc.getResistLevel()))
		{
			damage = (human.getMagicDamage() - orc.getResistLevel());
			orc.minusHp(damage);
		}
	}
}

void drawBot(float x, float y)
{
	D3DXMATRIX meshMat, meshScale, meshRotate, meshTranslate;

	D3DXMatrixTranslation(&meshTranslate, x, 1.0f, y);
	//D3DXMatrixRotationY(&meshRotate, timeGetTime()/500.0f);
	D3DXMatrixScaling(&meshScale, 0.4f, 0.4f, 0.4f);

	D3DXMatrixMultiply(&meshMat, &meshScale, &meshTranslate);
	//D3DXMatrixMultiply(&meshMat, &meshMat, &meshRotate);

	pd3dDevice->SetTransform(D3DTS_WORLD, &meshMat);

	pd3dDevice->SetMaterial(&yellow);

	sphereMesh->DrawSubset(0);
}

void moveBot()
{
	float allianceTotal = 0;
	float hordeTotal = 0;

	if(turn == 3)
	{
		//Calculates the difference distance between botX,botY to Horde and Alliance's X,Y
		//allianceTotal = (fabs(((curBoxPosY) - (curAlliancePosY)))) + (fabs(((curBoxPosX) - (curAlliancePosX))));
		//hordeTotal = (fabs(((curBoxPosY) - (curHordePosY)))) + (fabs(((curBoxPosX) - (curHordePosX))));

		if(allianceTotal >= hordeTotal)
		{
			//GO AFTER ALLIANCE
		}
		else
		{
			//GO AFTER HORDE
		}
	}
}

bool collision(int x, int y)
{
	int checkX = x;
	int checkY = y;
	double collisionX = 32;
	double collisionY = 13;

	if (turn == 1)
	{
		for (int p = hordeY; p <= 5; p++)
		{
			collisionX = collisionX * 1.035;
			collisionY = collisionY * 1.072;
		}
		collisionX = collisionX * .75;
		collisionY = collisionY * .75;
		checkX = curAlliancePosX - checkX;
		checkY = curAlliancePosY - checkY;
		if (checkX < 0)
			checkX = checkX * -1;
		if (checkY < 0)
			checkY = checkY * -1;
		if (checkX < collisionX && checkY < collisionY)
			return true;
		else
			return false;
	}
	else
	{
		for (int p = allianceY; p <= 5; p++)
		{
			collisionX = collisionX * 1.035;
			collisionY = collisionY * 1.072;
		}
		collisionX = collisionX * .75;
		collisionY = collisionY * .75;
		checkX = curHordePosX - checkX;
		checkY = curHordePosY - checkY;
		if (checkX < 0)
			checkX = checkX * -1;
		if (checkY < 0)
			checkY = checkY * -1;
		if (checkX < collisionX && checkY < collisionY)
			return true;
		else
			return false;
	}
}

void PrintText(char *text)
{
	D3DCOLOR fontcolor = D3DCOLOR_ARGB(255, 0, 0, 0);

	RECT rct;
	rct.left=10;
	rct.right=rct.left+300;
	rct.top=10;
	rct.bottom=rct.top+40;

	font2->DrawText(NULL, text, -1, &rct, DT_WORDBREAK, fontcolor );
}